class DB {
  constructor() {
    this.mysql = require("mysql");
    this.config = require("./db.config");
  }
  query(sql, params, callBack) {
    //1.创建mysql连接对象
    const connection = this.mysql.createConnection(this.config);
    //2.打开
    connection.connect((err) => {
      if (err) {
        console.log("数据库连接失败");
        throw err;
      }
    });
    //3.执行sql查询
    connection.query(sql, params, (err, results, fields) => {
      if (err) {
        console.log("数据库操作失败");
        throw err;
      }
      callBack && callBack({ results, fields });
    });
    //4.关闭连接
    connection.end((err) => {
      if (err) {
        console.log("数据库关闭失败");
        throw err;
      }
    });
  }

  queryAsync(sql, params) {
    const self = this;
    return new Promise((resolve, reject) => {
      //1.创建mysql连接对象
      const connection = self.mysql.createConnection(this.config);
      //2.打开
      connection.connect((err) => {
        if (err) {
          console.log("数据库连接失败");
          reject(err);
          return;
        }
      });
      //3.执行sql查询
      connection.query(sql, params, (err, results, fields) => {
        if (err) {
          console.log("数据库操作失败");
          reject(err);
          return;
        }
        resolve({
          results,
          fields,
        });
      });
      //4.关闭连接
      connection.end((err) => {
        if (err) {
          console.log("数据库关闭失败");
          reject(err);
          return;
        }
      });
    });
  }
}

module.exports = new DB();
